package com.yix.util;

import java.sql.*;

public class DBUtil {
    private static final String DBURL = "jdbc:postgresql://localhost:5432/";
    private static final String DATABASEURL = "jdbc:postgresql://localhost:5432/jdbc_demo_db";

    private static final String USER = "postgres";
    private static final String PASSWORD = "sp@73653$$$";

    static {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getPGConnection() throws SQLException {
        return DriverManager.getConnection(DBURL, USER, PASSWORD);
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DATABASEURL, USER, PASSWORD);
    }

    public static Boolean checkDatabaseExists(String databaseName) {
        Boolean result = true;
        String checkDatabaseSql = "SELECT 1 FROM pg_database WHERE datname  = ?";

        try (Connection conn = getPGConnection();
             PreparedStatement pstmt = conn.prepareStatement(checkDatabaseSql)) {
            pstmt.setString(1, databaseName);

            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                System.out.println("数据库 '" + databaseName + "' 存在");
            } else {
                result = false;
                System.out.println("数据库 '" + databaseName + "' 不存在");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}